import unitService from "@/api/services/base/unitService";
import { TableToolbar } from "@/components/grid/TableToolbar";
import useDictionary from "@/hooks/system/useDictionary";
import { t } from "@/locales/i18n";
import { Button, Card, Drawer, Form, Input, Select, Space } from "antd";
import Table, { type ColumnsType } from "antd/es/table";
import { useEffect, useMemo, useState } from "react";
import { toast } from "sonner";
import type { Unit } from "./entity";
import TableDictTag from "@/components/grid/TableDictTag";

export default function UnitPage() {
	const [loading, setLoading] = useState(false);
	const [queryParams, setQueryParams] = useState({
		unitCode: null,
		unitName: null,
		page: 1,
		pageSize: 10,
	});
	const [total, setTotal] = useState(0);
	const [list, setList] = useState<Unit[]>([]);
	const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([]);
	const [tableSize, setTableSize] = useState<"large" | "middle" | "small">("middle");
	const [drawerVisible, setDrawerVisible] = useState(false);
	const [editingData, setEditingData] = useState<Unit | null>(null);
	const [form] = Form.useForm();
	const [isView, setIsView] = useState(true); // 控制表单禁用状态

	//字典项
	const primaryFlagOptions = useDictionary("system_true_false");
	const statusOptions = useDictionary("system_status");

	const [tableScrollY, setTableScrollY] = useState(0);
	const PAGE_OFFSET_HEIGHT = 403; 

	const updateTableHeight = () => {
    const newHeight = window.innerHeight - PAGE_OFFSET_HEIGHT;
    setTableScrollY(newHeight > 200 ? newHeight : 200); // 保证最小高度
  };

	useEffect(() => {
    updateTableHeight(); // 初始化
    window.addEventListener("resize", updateTableHeight);
    return () => window.removeEventListener("resize", updateTableHeight);
  }, []);

	// 定义表格列
	const columns: ColumnsType<Unit> = [
		{
			title: "单位编码",
			key: "unitCode",
			dataIndex: "unitCode",
		},
		{
			title: "单位名称",
			key: "unitName",
			dataIndex: "unitName",
		},
		{
			title: "是否主单位",
			key: "primaryFlag",
			dataIndex: "primaryFlag",
			render:(_, record) => (
				<TableDictTag dictCode="system_true_false" value={record.primaryFlag}/>
			)
		},
		{
			title: "与主单位换算",
			key: "changeRate",
			dataIndex: "changeRate",
		},
		{
			title: "状态",
			key: "status",
			dataIndex: "status",
			render:(_, record) => (
				<TableDictTag dictCode="system_status" value={record.status}/>
			)
		},
		{
			title: "描述",
			key: "description",
			dataIndex: "description",
		},
		{
			title: "操作",
			key: "operation",
			align: "center",
			width: 100,
			render: (_, record) => (
				<Space>
					<Button type="link" onClick={() => handleView(record)}>
						{t("common.view")}
					</Button>
					<Button type="link" onClick={() => handleEdit(record)}>
						{t("common.edit")}
					</Button>
				</Space>
			),
		},
	];

	// 状态管理
	const [selectedValues, setSelectedValues] = useState<string[]>(() =>
		columns.filter((col) => col.key !== "operation").map((col) => String(col.key!)),
	);

	// 处理过滤后的列配置
	const filteredColumns = useMemo(() => {
		return [
			// 显示选中的列
			...columns.filter(
				(col) => selectedValues.includes(String(col.key)) || col.key === "operation", // 始终包含操作列
			),
		].sort((a, b) => {
			// 保持原始顺序
			const originalIndex = columns.findIndex((c) => c.key === a.key);
			const targetIndex = columns.findIndex((c) => c.key === b.key);
			return originalIndex - targetIndex;
		});
	}, [selectedValues]);

	const fetchPageList = () => {
		setLoading(true);
		unitService
			.pageList(queryParams)
			.then((res) => {
				setList(res.records);
				setTotal(res.total);
			})
			.catch((error) => {
				console.log(error);
				toast.error("获取数据失败！", error);
			})
			.finally(() => {
				setLoading(false);
			});
	};

	//组件加载时获取组织机构数据
	useEffect(() => {
		fetchPageList();
	}, [queryParams]);

	//触发分页控件
	const handlePageChange = (newPage: number, newPageSize: number) => {
		setQueryParams((prev) => ({
			...prev,
			page: newPage,
			pageSize: newPageSize,
		}));
	};

	const handleEdit = (unit: Unit) => {
		setEditingData(unit);
		form.setFieldsValue(unit);
		setDrawerVisible(true);
		setIsView(false);
	};

	/**
	 * 查看单位信息
	 * @param unit 单位信息
	 */
	const handleView = (unit: Unit) => {
		setEditingData(unit);
		form.setFieldsValue(unit);
		setIsView(true);
		setDrawerVisible(true);
	};

	const handleSubmit = async (values) => {
		try {
			setLoading(true);
			if (editingData) {
				await unitService.update({ ...values, id: editingData.id });
				toast.success("更新单位信息成功");
			} else {
				await unitService.add(values);
				toast.success("创建单位信息成功");
			}
			setDrawerVisible(false);
			setEditingData(null);
			form.resetFields();
			fetchPageList();
		} catch (error) {
			toast.error(`${error.message}`);
		} finally {
			setLoading(false);
		}
	};

	const handleDrawerClose = () => {
		setDrawerVisible(false);
		setEditingData(null);
		form.resetFields();
	};

	const handleAdd = () => {
		setEditingData(null);
		form.resetFields();
		setDrawerVisible(true);
		setIsView(false);
	};

	//删除单位信息方法
	const handleDelete = async () => {
		try {
			setLoading(true);
			await unitService.remove(selectedRowKeys);
			toast.success("删除单位信息成功");
			setSelectedRowKeys([]); // 清空选中项
			fetchPageList(); // 重新加载列表
		} catch (error) {
			toast.error(`删除失败: ${error.message}`);
		} finally {
			setLoading(false);
		}
	};

	return (
		<>
			{/* 查询条件 */}
			<Card className="mb-4">
				<Form
					layout="inline"
					onFinish={(values) => {
						// 处理查询条件
						setQueryParams((prev) => ({
							...prev,
							...values,
							page: 1,
						}));
					}}
				>
					<Form.Item name="unitCode" label="单位编码">
						<Input placeholder="请输入单位编码" allowClear />
					</Form.Item>
					<Form.Item name="unitName" label="单位名称">
						<Input placeholder="请输入单位名称" allowClear />
					</Form.Item>
					<Form.Item>
						<Button type="primary" htmlType="submit">
							查询
						</Button>
						<Button
							className="ml-2"
							onClick={() => {
								// 重置查询条件
								setQueryParams({ page: 1, pageSize: 10 });
							}}
						>
							重置
						</Button>
					</Form.Item>
				</Form>
			</Card>
			<div className="h-4" />
			{/* 表格数据 */}
			<Card>
				<div className="flex justify-between mb-4">
					<div className="flex gap-2">
						<Button type="primary" onClick={handleAdd}>
							新增
						</Button>
						<Button danger disabled={selectedRowKeys.length === 0} onClick={handleDelete}>
							删除
						</Button>
					</div>
					<TableToolbar
						onRefresh={() => setQueryParams((prev) => ({ ...prev }))}
						onSizeChange={setTableSize}
						columns={columns}
						selectedValues={selectedValues}
						onColumnChange={setSelectedValues}
					/>
				</div>
				<Table
					rowKey="id"
					size={tableSize}
					loading={loading}
					pagination={{
						total,
						current: queryParams.page,
						pageSize: queryParams.pageSize,
						onChange: handlePageChange,
					}}
					columns={filteredColumns}
					dataSource={list}
					rowSelection={{
						type: "checkbox",
						selectedRowKeys: selectedRowKeys,
						onChange: (selectedKeys) => {
							setSelectedRowKeys(selectedKeys as string[]);
						},
					}}
					scroll={{ y: tableScrollY }}
				/>
			</Card>
			{/* 编辑页面 */}
			<Drawer
				title={editingData ? "编辑单位信息" : "新增单位信息"}
				width={480}
				open={drawerVisible}
				onClose={handleDrawerClose}
				footer={
					<div className="flex justify-end gap-2">
						<Button onClick={handleDrawerClose}>取消</Button>
						{!isView && (
							<Button type="primary" onClick={() => form.submit()}>
								确定
							</Button>
						)}
					</div>
				}
			>
				<Form form={form} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} onFinish={handleSubmit} disabled={isView}>
					<Form.Item name="unitCode" label="单位编码">
						<Input placeholder="请输入单位编码" />
					</Form.Item>
					<Form.Item name="unitName" label="单位名称">
						<Input placeholder="请输入单位名称" />
					</Form.Item>
					<Form.Item name="primaryFlag" label="是否主单位">
						<Select options={primaryFlagOptions} />
					</Form.Item>
					<Form.Item name="changeRate" label="与主单位换算">
						<Input placeholder="请输入与主单位换算" />
					</Form.Item>
					<Form.Item name="description" label="描述">
						<Input placeholder="请输入描述" />
					</Form.Item>
				</Form>
			</Drawer>
		</>
	);
}
